import GameConst from "../GameConst";
import Utils from "../utils";
import MapItem from "../../../../ui/MapItem";
import ClickableObject from "../ClickableObject";
import SoundButton from "../SoundsButton";

export default class MapMenu{
    constructor(manger) {
        this.manager = manger;
        this.firstShow = true;
        this.isMoving = false;
        this.pointerIsMoving = false;
        this.currentLevel = 0;
        this.downPos = new Laya.Point;
        this.speed = 0;
        this.isDown = false;
        this.dragSpeed = 0;
        this.lastSpeed = 0;
        this.downY = 0;
        GameConst.levelToUnlock = -1;
        this.isLevelUnlocking = false;
        this.isPlayPressed = false;
        this.clickObjs = [];
        this.sprite = new Laya.Sprite;
        this.scrollSprite = new Laya.Sprite;
        this.scrollSprite.name = "scrollSprite";
        this.sprite.addChild(this.scrollSprite);
        for (var i = 0; i <= 3; ++i) {
            var img = new Laya.Image("map/mapbg"+i+".png");
            img.sizeGrid = "0,3,0,3,0";
            img.width = GameConst.SCREEN_W;
            img.y = i*500;
            this.scrollSprite.addChild(img);
        }
        this.clouds = [];
        for(var i=0;i<4;i++){
            var cloud = Utils.createSprite('map/cloud.png');
            this.scrollSprite.addChild(cloud);
            this.clouds.push(cloud);
        }
        
        this.plane = Utils.createSprite('map/plane.png');
        this.scrollSprite.addChild(this.plane);

        var top = new Laya.Image('map/top.png');
        this.sprite.addChild(top);
        // height
        var pjson = Laya.loader.getRes('prefabs/mapitem.json');
        
        var list = new Laya.List();
        list.width = GameConst.SCREEN_W;
        list.height = 800;
        list.itemRender = pjson;
        list.repeatX = MapMenu.LIST_X_REPEAT;
        list.spaceX = MapMenu.LIST_SPACEX;
        list.spaceY = MapMenu.LIST_SPACEY;
        this.sprite.addChild(list);
        list.renderHandler = Laya.Handler.create(this,this.onItemRender,null,false);
        this.list = list;
        list.selectEnable = true;
        list.selectHandler = Laya.Handler.create(this,this.onItemSelect,null,false);
        list.y = GameConst.SHIFT_H;

        var btn = new SoundButton(true,'map/btn_music_');
        btn.x = 10;
        this.sprite.addChild(btn);
        var clickbtn = new ClickableObject(btn);
        clickbtn.callback = btn.callback;
        clickbtn.thisObj = btn;
        this.clickObjs.push(clickbtn);
        btn.refresh();
        btn = new SoundButton(false,'map/btn_sounds_');
        btn.x = 150;
        this.sprite.addChild(btn);
        clickbtn = new ClickableObject(btn);
        clickbtn.callback = btn.callback;
        clickbtn.thisObj = btn;
        this.clickObjs.push(clickbtn);
        btn.refresh();

        var left = new Laya.Sprite();
        var img = Utils.createSprite('map/btn_next.png');
        img.scaleX = -1;
        img.pivotX = 165;
        left.addChild(img);
        var right = Utils.createSprite('map/btn_next.png');
        this.sprite.addChild(left);
        this.sprite.addChild(right);
        var clickLeft = new ClickableObject(left);
        var clickRight = new ClickableObject(right);
        this.clickObjs.push(clickLeft);
        this.clickObjs.push(clickRight);
        this.leftBtn = left;
        this.rightBtn = right;
        clickLeft.callback = this.onPageLeftClick;
        clickRight.callback = this.onPageRightClick;

        // var button = new SoundButton(2, this.sprite, 670, 200);
        // this.animatedButtons.push(button);
        // this.clickables.push(button);
        // var button = new SoundButton(0, this.sprite, 570, 215 - 50);
        // this.animatedButtons.push(button);
        // this.clickables.push(button);
    }

    onPageLeftClick(){
        var p = this.list.page-1;
        if(p>=0){
            this.list.page = p;
        }
    }

    onPageRightClick(){
        var p = this.list.page+1;
        this.list.page = p;
    }

    onItemSelect(cell,index){
        var source = cell.dataSource;
        if(source.lock){
            return;
        }
        GameConst.levelManager.prepareToLoadLevel(index);
    }
    onItemRender(cell,index){
        var mi = cell.getComponent(MapItem);
        mi.onItemRender();
    }

    randomClound(cloud){
        var scale = (2+Utils.getInt(9))*0.1;
        cloud.scale(scale,scale,true);
        cloud.y = 300+Utils.getInt(GameConst.FULL_SCREEN_H-200);
        cloud.speed = Utils.getInt(15)+1;
        cloud.alpha = 0.2+(Math.random()*0.8);
    }
    randomPlane(){
        this.plane.visible = false;
        var rnd = Utils.getInt(16);
        this.plane.showTime = Laya.timer.currTimer+rnd*1000;
        var speed = Utils.getInt(120)+40;

        var scx = rnd%2==0?1:-1;

        var p = Utils.cjp(speed*scx,speed);
       
        this.plane.scaleX = scx;
        this.plane.speedX = -1*p.x;
        this.plane.speedY = p.y;
        this.plane.y = Utils.getInt(GameConst.FULL_SCREEN_H/2)+GameConst.FULL_SCREEN_H/2;
        this.plane.x = scx>0?GameConst.SCREEN_W:1;
    }
    show() {
        var lvllist = [];
        var data = GameConst.levelManager.data;
        var currentLvl = GameConst.levelManager.maxLvl();
        for(var i=0;i<data.length;i++){
            lvllist.push({
                lvl:i+1,
                star:data[i].stars,
                lock:i>currentLvl
            });
        }
        this.list.array = lvllist;
        this.list.page = Math.floor((0.5+currentLvl)/MapMenu.LIST_PAGESIZE);
        Laya.stage.addChild(this.sprite);
        this.onResize();
        this.isLevelUnlocking = GameConst.levelToUnlock > 0;
        this.isPlayPressed = false;
        this.isMoving = false;
        this.pointerIsMoving = false;
        this.speed = 0;
        this.isDown = false;
        this.update(0);

        for(var i=0;i<this.clouds.length;i++){
            var cloud = this.clouds[i];//new Laya.Sprite;//this.clouds[i];
            cloud.x = Utils.getInt(GameConst.SCREEN_W+cloud.width)-cloud.width;
            this.randomClound(cloud);
        }
        this.randomPlane();

        // this.firstShow = GameConst.levelManager.isFirstLoad && false;
        // if (this.firstShow) {
        //     GameConst.levelManager.isFirstLoad = false;
        //     this.firstShow = false;
        //     this.scrollSprite.y = 0;
        //     var n = 1;
        //     this.scroll(GameConst.ACTUAL_H - this.height, 4e3 / n, 1e3 / n);
        // }
        //  else if (this.isLevelUnlocking) {
        //     var r = this.buttons[GameConst.levelToUnlock];
        //     Laya.Tween.to(r,{
        //         scaleX: r.scaleX * 1.4,
        //         scaleY: r.scaleY * 1.4,
        //         alpha: .1
        //     }, 500, Laya.Ease.cubicOutLaya.Handler.create(this,this.onButtonHide));
        // } else {
        // }
        this.updatePointerData();
        this.lastClickDt = Laya.timer.currTimer;
    };

    

    destroy() {
    };
    onDown(x,y) {
        // if (this.isLevelUnlocking)
        //     return;
        // this.downPos = this.scrollSprite.globalToLocal(x, y);
        // this.isDown = true;
        // this.dragSpeed = 0;
        // this.downY = y;
        //e.nativeEvent && e.preventDefault && e.preventDefault();
    };

    onUp(x,y) {
        // if (this.isLevelUnlocking)
        //     return;
        // this.isDown = false;
        // this.speed = this.lastSpeed;
        // var t = Utils.sign(this.speed);
        // this.speed = t * Utils.limit(Math.abs(this.speed), 0, 15);
        // Laya.Tween.to(this, {
        //     speed: 0
        // }, 600, Laya.Ease.cubicOut);
        // //e.nativeEvent && e.preventDefault && e.preventDefault();
        this.onClick(x,y);
        // this.lastClickDt = Laya.timer.currTimer;
    };

    update(t) {
        if(!this.listBound){
            this.onResize();
            return;
        }else{
            if(Laya.timer.currTimer>this.updelay){
                var time = 0;
                var pg = this.list.page;
                for(var i=0;i<MapMenu.LIST_PAGESIZE;i++){
                    var cell = this.list.getCell(i+pg*MapMenu.LIST_PAGESIZE);
                    if(cell){
                        time+=cell.getComponent(MapItem).play(time);
                    }else{
                        console.log('cell is null');
                    }
                }
                this.updelay = Laya.timer.currTimer+time*1000/60+10000;
            }
        }
        for(i=0;i<this.clouds.length;i++){
            var cloud = this.clouds[i];
            var x = cloud.x;
            x += cloud.speed*t;
            if(x>GameConst.SCREEN_W){
                this.randomClound(cloud);
                x = -100-cloud.width;
            }
            cloud.x = x;
        }
        if(this.plane.visible){
            this.plane.x += this.plane.speedX*t;
            this.plane.y -= this.plane.speedY*t;
            if(this.plane.x>GameConst.SCREEN_W+150||this.plane.x<-100){
                this.randomPlane();
            }
        }else{
            if(this.plane.showTime<Laya.timer.currTimer){
                this.plane.visible = true;
            }
        }
        // for (var n = 0; n < GameConst.LEVEL_AMOUNT; ++n) {
        //     var i = this.buttons[n];
        //     if(!i){
        //         return;
        //     }
        //     var s = i.localToGlobal(0, 0);
        //     i.visible = n == GameConst.levelToUnlock || GameConst.levelManager.data[n].state == GameConst.CLOSED_STATE && !(s.y > GameConst.ACTUAL_H + 200 || s.y < -200);
        // }
        if(this.lastClickDt+3000 < Laya.timer.currTimer){
            this.lastClickDt = Laya.timer.currTimer+5000;
        }
    };

    hide () {
        this.sprite.releaseMouseEvent;
        Utils.removeClip(this.sprite);
        //this.pointer.getPart(0).releaseMouseEvent();
    };

    onClick(stageX,stageY) {
        for(var i=0;i<this.clickObjs.length;i++){
            if(this.clickObjs[i].checkClick(stageX,stageY)){
                if(this.clickObjs[i].thisObj){
                    this.clickObjs[i].callback.call(this.clickObjs[i].thisObj);
                }else{
                    this.clickObjs[i].callback.call(this);
                }
                
                return;
            }
        }
        var lvl = this.getIndex(stageX,stageY);
        if(lvl<=GameConst.levelManager.maxLvl()){
            GameConst.levelManager.prepareToLoadLevel(lvl);
        }
    };

    onResize() {
        var bound = this.list.getBounds();
        if(bound.width<1 || !this.list.array){
            return;
        }
        this.listBound = bound;
        this.list.x = (GameConst.SCREEN_W-bound.width)/2;
        
        var first = this.list.getCell(0);
        var bd = first.getBounds();
        var gpoint = first.localToGlobal(Utils.cjp(bd.x,bd.y));
        this.firstBound = new Laya.Rectangle(gpoint.x,gpoint.y,bd.width,bd.height);
        this.updelay = Laya.timer.currTimer+2000;


        this.leftBtn.y = this.list.y+900;
        this.rightBtn.y = this.list.y+900;
        this.leftBtn.x = GameConst.SCREEN_W/2-60-165;
        this.rightBtn.x = GameConst.SCREEN_W/2+60;

        for(var i=0;i<this.clickObjs.length;i++){
            var sp = this.clickObjs[i].sprite;
            var bd = sp.getBounds();
            this.clickObjs[i].setRect(0,0,bd.width,bd.height);
        }
    };

    getIndex(stx,sty){
        var cx = MapMenu.LIST_SPACEX;
        var morex = cx-this.firstBound.width;
        if(stx<this.firstBound.x||stx>this.firstBound.x+cx*MapMenu.LIST_X_REPEAT-morex){
            return;
        }
        var x = stx-this.firstBound.x;
        //点击到间距中间了
        if(x%cx>this.firstBound.width){
            return;
        }
        var cy = MapMenu.LIST_SPACEY;
        var morey = cy-this.firstBound.height;
        if(sty<this.firstBound.y||sty>this.firstBound.y+cy*5-morey){
            return;
        }
        var y = sty-this.firstBound.y;
        //点击到间距中间了
        if(y%cy>this.firstBound.height){
            return;
        }
        
        var row,col; // 行,列
        col = Math.floor(x/cx);
        row = Math.floor(y/cy);
        var idx = row*MapMenu.LIST_X_REPEAT+col
        if(this.list.page>0){
            idx+=MapMenu.LIST_PAGESIZE*(this.list.page);
        }
        return idx;
    }
    
    
}
MapMenu.LIST_SPACEX = 170;
MapMenu.LIST_SPACEY = 180;
MapMenu.LIST_X_REPEAT = 4;
MapMenu.LIST_PAGESIZE = 20;


// MapMenu.prototype.loadMain = function (e) {
//     manager.show(manager.mainMenu);
// };
MapMenu.prototype.updatePointerData = function () {
    // var e = GameConst.levelManager.data[this.currentLevel];
    // var t = e.stars;
    // var n = e.targetSpriteName;
    // var r = this.pointerSprites[0];
    // r.text = (e.levelNumber + 1).toString();
    // r.pivotX = r.getBounds().width / 2;
    // r.pivotY = r.getBounds().height / 2;
    // for (var i = 0; i < 3; ++i) {
    //     var s = this.pointerSprites[i + 1];
    //     s.visible = i < t;
    // }
    // s = this.pointerSprites[4];
    // s.gotoAndStop(n);
    // s.scale(1,1);
    // var bound = s.getBounds();
    // s.pivotX = bound.width / 2;
    // s.pivotY = bound.height / 2;
    // s.scaleX = s.scaleY = Math.min(45 / bound.width, 45 / bound.height);
};

MapMenu.prototype.fastUnlock = function (e) {
    // GameConst.levelToUnlock = -1;
    // this.buttons[e].visible = false;
    // Utils.removeClip(this.buttons[e]);
};
MapMenu.prototype.onButtonHide = function () {
};





